import logging

import global_vars
import telegram
from bot_constant import FORWARD_LIST
from main.command import command_listener
from telegram.ext import MessageHandler, Filters
from telegram.ext.dispatcher import DispatcherHandlerStop
from telegram import TelegramError

from main.utils import get_forward_index, send_both_side, get_plugin_priority

logger = logging.getLogger("CTB." + __name__)
logger.debug(__name__ + " loading")

global_vars.create_variable('QQTG_DRIVE', list())
global_vars.create_variable('TGQQ_DRIVE', list())
for item in FORWARD_LIST:
    global_vars.QQTG_DRIVE.append(item["DRIVE_MODE"])
    global_vars.TGQQ_DRIVE.append(item["DRIVE_MODE"])


def generate_message(forward_index: int):
    return "\nDrive mode status:\nQQ->TG: {}\nTG->QQ: {}".format(
        "drive(not relaying)" if global_vars.QQTG_DRIVE[forward_index] else "park(relaying)",
        "drive(not relaying)" if global_vars.TGQQ_DRIVE[forward_index] else "park(relaying)",
    )


@command_listener("drive qqtg on", "qqtgd", description="关闭qq到tg的转发")
def qqtg_drive_on(forward_index: int,
                  tg_group_id: int = None,
                  tg_user: telegram.User = None,
                  tg_message_id: int = None,
                  tg_reply_to: telegram.Message = None,
                  qq_group_id: int = None,
                  qq_discuss_id: int = None,
                  qq_user: int = None):
    global_vars.QQTG_DRIVE[forward_index] = True
    return send_both_side(forward_index, generate_message(forward_index),
                          qq_group_id, qq_discuss_id, tg_group_id, tg_message_id)


@command_listener("drive qqtg off", "qqtgp", description="打开qq到tg的转发")
def qqtg_drive_off(forward_index: int,
                   tg_group_id: int = None,
                   tg_user: telegram.User = None,
                   tg_message_id: int = None,
                   tg_reply_to: telegram.Message = None,
                   qq_group_id: int = None,
                   qq_discuss_id: int = None,
                   qq_user: int = None):
    global_vars.QQTG_DRIVE[forward_index] = False
    return send_both_side(forward_index, generate_message(forward_index),
                          qq_group_id, qq_discuss_id, tg_group_id, tg_message_id)


@command_listener("drive tgqq on", "tgqqd",  description="关闭tg到qq的转发")
def tgqq_drive_on(forward_index: int,
                  tg_group_id: int = None,
                  tg_user: telegram.User = None,
                  tg_message_id: int = None,
                  tg_reply_to: telegram.Message = None,
                  qq_group_id: int = None,
                  qq_discuss_id: int = None,
                  qq_user: int = None):
    global_vars.TGQQ_DRIVE[forward_index] = True
    return send_both_side(forward_index, generate_message(forward_index),
                          qq_group_id, qq_discuss_id, tg_group_id, tg_message_id)


@command_listener("drive tgqq off", "tgqqp",  description="打开tg到qq的转发")
def tgqq_drive_off(forward_index: int,
                   tg_group_id: int = None,
                   tg_user: telegram.User = None,
                   tg_message_id: int = None,
                   tg_reply_to: telegram.Message = None,
                   qq_group_id: int = None,
                   qq_discuss_id: int = None,
                   qq_user: int = None):
    global_vars.TGQQ_DRIVE[forward_index] = False
    return send_both_side(forward_index, generate_message(forward_index),
                          qq_group_id, qq_discuss_id, tg_group_id, tg_message_id)


@command_listener("drive mode on", "drive",  description="关闭tg->qq和qq->tg转发")
def drive_all(forward_index: int,
              tg_group_id: int = None,
              tg_user: telegram.User = None,
              tg_message_id: int = None,
              tg_reply_to: telegram.Message = None,
              qq_group_id: int = None,
              qq_discuss_id: int = None,
              qq_user: int = None):
    tgqq_drive_on(forward_index, tg_group_id, tg_user, tg_message_id,
                  tg_reply_to, qq_group_id, qq_discuss_id, qq_user)
    qqtg_drive_on(forward_index, tg_group_id, tg_user, tg_message_id,
                  tg_reply_to, qq_group_id, qq_discuss_id, qq_user)
    return send_both_side(forward_index, generate_message(forward_index),
                          qq_group_id, qq_discuss_id, tg_group_id, tg_message_id)


@command_listener("drive mode off", "park",  description="打开tg->qq和qq->tg转发")
def park_all(forward_index: int,
             tg_group_id: int = None,
             tg_user: telegram.User = None,
             tg_message_id: int = None,
             tg_reply_to: telegram.Message = None,
             qq_group_id: int = None,
             qq_discuss_id: int = None,
             qq_user: int = None):
    tgqq_drive_off(forward_index, tg_group_id, tg_user, tg_message_id,
                   tg_reply_to, qq_group_id, qq_discuss_id, qq_user)
    qqtg_drive_off(forward_index, tg_group_id, tg_user, tg_message_id,
                   tg_reply_to, qq_group_id, qq_discuss_id, qq_user)
    return send_both_side(forward_index, generate_message(forward_index),
                          qq_group_id, qq_discuss_id, tg_group_id, tg_message_id)


def tgqq_drive_handler(bot: telegram.Bot, update: telegram.Update):
    message: telegram.Message = update.effective_message
    group_id = message.chat_id
    forward_index = get_forward_index(tg_group_id=int(group_id))

    def drive():
        if message.text is None:
            logger.debug("message refused:{}".format(message))
            raise DispatcherHandlerStop()
        if message.text.startswith("/"):
            pass
        else:
            logger.debug("message refused:{}".format(message))
            raise DispatcherHandlerStop()
    if forward_index == -1:
        drive()
    if global_vars.TGQQ_DRIVE[forward_index]:
        drive()


global_vars.dp.add_handler(MessageHandler(
    Filters.all, tgqq_drive_handler, edited_updates=True),get_plugin_priority(__name__))


@global_vars.qq_bot.on_message("group", "discuss", group=get_plugin_priority(__name__))
def qqtg_drive_handler(context: dict):
    print(context)
    group_id = context.get('group_id')
    discuss_id = context.get('discuss_id')
    forward_index = get_forward_index(qq_group_id=group_id,
                                      qq_discuss_id=discuss_id)

    def drive():
        if context["raw_message"].startswith("/"):
            return {"pass":True}
        else:
            logger.debug("message refused:{}".format(context))
            return ""
    if forward_index == -1:
        return drive()
    if global_vars.QQTG_DRIVE[forward_index]:
        return drive()
    return {"pass": True}
